/**
 * Copyright (c) 2006 Amgad S Youssef
 * All Rights Reserved.
 * Licensed under the Eclipse Public License - v 1.0
 * For more information see http://www.eclipse.org/legal/epl-v10.html
 */
package org.eclipsejcde.jcwde.dialogs;

import java.util.ArrayList;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipsejcde.core.JCDECore;

/**
 * @author Amgad S Youssef
 *
 */
public class JCAppletSelectionDialog extends ElementListSelectionDialog {

	public JCAppletSelectionDialog(Shell parent) throws JavaModelException {
		super(parent, new JCAppletLabelProvider());
		ICompilationUnit[] workspaceJCApplets = JCDECore.getWorkspaceJCApplets();
		setElements(workspaceJCApplets);
		setMultipleSelection(true);
		setTitle("JCWDE Simulator");
		setMessage("Select the Java Card Applets you want to deploy on JCWDE Simulator");
		setDialogHelpAvailable(false);
	}

	public ICompilationUnit[] getSelectedJCApplets() {
		Object[] selectedObjects = getResult();
		ArrayList compilationUnitsList = new ArrayList();
		for (int i = 0; i < selectedObjects.length; i++) {
			if (selectedObjects[i] instanceof ICompilationUnit) {
				ICompilationUnit compilationUnit = (ICompilationUnit) selectedObjects[i];
				compilationUnitsList.add(compilationUnit);
			}
		}
		ICompilationUnit[] compilationUnits = new ICompilationUnit[compilationUnitsList.size()];
		compilationUnitsList.toArray(compilationUnits);
		return compilationUnits;
	}

	private static class JCAppletLabelProvider extends LabelProvider {

		@Override
		public String getText(Object element) {
			if (element instanceof ICompilationUnit) {
				ICompilationUnit compilationUnit = (ICompilationUnit) element;
				IType type = compilationUnit.findPrimaryType();
				return type.getFullyQualifiedName();
			}
			return super.getText(element);
		}

	}

}
